package com.leyantech.ecp.agenx.translator.filter.client;

import com.leyantech.ecp.agenx.common.config.ConfigManager;

import com.google.inject.Singleton;
import io.vertx.core.json.JsonObject;
import lombok.extern.slf4j.Slf4j;

/**
 * @author eahau, {@literal <eahau@foxmail.com>}
 * @date 2022-11-15.
 */
@Slf4j
@Singleton
public class ExpireMessageFilter implements ClientMessageFilter {

  @Override
  public boolean test(JsonObject jsonObject) {

    final JsonObject header = jsonObject.getJsonObject("header");

    Long obtainedMills = header.getLong("ts");
    if (obtainedMills != null) {
      final Long receivedTimestamp = jsonObject.getJsonObject("body").getLong("ts");
      final long delta = receivedTimestamp - obtainedMills;
      if (delta <= 0) {
        log.warn("Maybe Client time is {} ms faster than Server time", -delta);
      }
      if (delta < ConfigManager.MESSAGE_EXPIRE_MILLS.get()) {
        return true;
      }
    }

    log.info("filter by ExpireMessage");
    return false;
  }

}
